package conson.tech.manage.app.service.impl;

import conson.tech.manage.api.app.constant.AppCommon;
import conson.tech.manage.api.app.dto.AppAdvertDTO;
import conson.tech.manage.api.app.dto.AppConfigDTO;
import conson.tech.manage.api.app.dto.AppGroupConfigDTO;
import conson.tech.manage.api.app.form.AppQueryForm;
import conson.tech.manage.app.entity.mobile.vo.*;
import conson.tech.manage.app.entity.pojo.*;
import conson.tech.manage.app.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: AppNewMobileServiceImpl
 * Description:
 * Author: HXL
 * Date: 2020/6/9 9:16 上午
 * Version: 1.0
 */
@Slf4j
@Service
public class AppNewMobileServiceImpl implements AppNewMobileService {

    @Autowired
    private AppAdvertService appAdvertService;
    @Autowired
    private AppPageConfigService appPageConfigService;
    @Autowired
    private AppConfigService appConfigService;
    @Autowired
    private AppGroupConfigService appGroupConfigService;
    @Autowired
    private AppUserRelationService appUserRelationService;
    @Autowired
    private AppVersionService appVersionService;

    @Override
    public IndexVo assembleAppMobilePageData(Long userId, Integer versionValue, AppQueryForm form) {
        List<AppPageConfig> list = appPageConfigService.queryAppPageConfigByPageType(form.getType(), versionValue);
        if (!CollectionUtils.isEmpty(list)){
            return buildIndexVo(list,form,userId,versionValue);
        }
        return null;
    }

    @Override
    public CreditModuleVo appQueryLetterBean(AppConfig appConfig, Integer versionValue,AppQueryForm form ) {
        List<AppConfigDTO> appConfigList = appConfigService.queryAppConfigList(appConfig, versionValue);
        CreditModuleVo creditModuleVo = new CreditModuleVo();
        if (!CollectionUtils.isEmpty(appConfigList)){
            List<IconVo> inviteList = new ArrayList<>();
            List<IconVo> exchangeList = new ArrayList<>();
            for (AppConfigDTO appConfigDTO : appConfigList) {
                if (!StringUtils.isEmpty(appConfigDTO.getName()) && appConfigDTO.getName().contains(AppCommon.CREDIT_EXCHANGE_NAME)) {
                    exchangeList.add(buildIconVo(appConfigDTO,form.getPlatformType()));
                    continue;
                }
                inviteList.add(buildIconVo(appConfigDTO,form.getPlatformType()));
            }
            creditModuleVo.setInviteList(inviteList);
            creditModuleVo.setExchangeList(exchangeList);
        }
        return creditModuleVo;
    }

    @Override
    public List<ModuleVo> queryAppGroupByType(AppQueryForm form, Integer versionValue) {
        List<AppGroupConfigDTO>  list = appGroupConfigService.queryAppGroupByType(form.getType(),versionValue);
        if (!CollectionUtils.isEmpty(list)){
            List<ModuleVo> moduleVoList = new ArrayList<>();
            list.stream().forEach(appGroupConfigDTO -> {
                ModuleVo moduleVo = new ModuleVo();
                moduleVo.setModuleName(appGroupConfigDTO.getName());
                moduleVo.setModulePicUrl(appGroupConfigDTO.getCustomIconUrl());
                List<AppConfigDTO> appConfigList = appGroupConfigDTO.getAppConfigList();
                if (!CollectionUtils.isEmpty(appConfigList)){
                    List<IconVo> linkList = new ArrayList<>();
                    appConfigList.stream().forEach(appConfigDTO -> {
                        linkList.add(buildIconVo(appConfigDTO,form.getPlatformType()));
                    });
                    moduleVo.setLinkList(linkList);
                }
                moduleVoList.add(moduleVo);
            });
            return moduleVoList;
        }
        return null;
    }

    @Override
    public ModuleVo queryGroupByGroupId(Long id, Integer versionValue,AppQueryForm form ) {
        AppGroupConfig appGroupConfig = appGroupConfigService.queryGroupByGroupId(id, versionValue);
        if (appGroupConfig != null){
            ModuleVo moduleVo = new ModuleVo();
            moduleVo.setModuleName(appGroupConfig.getName());
            moduleVo.setModulePicUrl(appGroupConfig.getCustomIconUrl());
            List<AppConfig> appConfigList = appGroupConfig.getAppConfigList();
            if (!CollectionUtils.isEmpty(appConfigList)){
                List<IconVo> list = new ArrayList<>();
                appConfigList.stream().forEach(appConfig ->list.add(buildIconVo(appConfig,form.getPlatformType())));
                moduleVo.setLinkList(list);
            }
            return moduleVo;
        }
        return null;
    }

    @Override
    public boolean saveIndex(Long userId, List<Long> iconIdList) {
        try {
            appUserRelationService.deleteByUserId(userId);
            List<AppUserRelation> relationList = new ArrayList<>();
            for (Long aLong : iconIdList) {
                AppUserRelation appUserRelation = new AppUserRelation();
                appUserRelation.setUserId(userId);
                appUserRelation.setIsUse(1);
                appUserRelation.setDelFlag(1);
                appUserRelation.setAppId(aLong);
                appUserRelation.setEndVersion(null);
                appUserRelation.setEndVersionValue(null);
                appUserRelation.setStartVersion(null);
                appUserRelation.setStartVersionValue(null);
                appUserRelation.setCreatedBy(userId+"");
                appUserRelation.setUpdatedBy(userId+"");
                relationList.add(appUserRelation);
            }
            int i = appUserRelationService.saveIndex(relationList);
            if (i >0) {
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            log.error("用户自定义icon保存出错:",e);
           return false;
        }
    }

    @Override
    public ConfigVo getVersionConfig(String version, Integer platformType) {
        List<AppVersion> versionList = appVersionService.queryAppVersionByVersionNum(version, platformType);
        if (!CollectionUtils.isEmpty(versionList)){
            ConfigVo vo = new ConfigVo();
            AppVersion appVersion = versionList.get(0);

            // 版本状态1最新版本2提示更新3不提示更新4强制更新
            if (appVersion.getVersionState() == AppCommon.VERSION_STATE_ONE || appVersion.getVersionState() == AppCommon.VERSION_STATE_THREE){
                vo.setForce("3"); //最新版本  不提示更新
            }else if (appVersion.getVersionState() == AppCommon.VERSION_STATE_TWO){//2提示更新
                vo.setForce("2");

            }else if (appVersion.getVersionState() == AppCommon.VERSION_STATE_FOUR){//强制更新
                vo.setForce("1");
            }
            AppVersion appVersion1 = null;
            if(appVersion.getVersionState() != AppCommon.VERSION_STATE_ONE) {
                List<AppVersion> newAppVersionList = appVersionService.queryNewVersionData(1, platformType);
                if (!CollectionUtils.isEmpty(newAppVersionList)){
                    appVersion1 = newAppVersionList.get(0);
                }
            }
            if (appVersion1 != null){
                vo.setUpdateContent(appVersion1.getPopupCopyWriting());
                if (appVersion.getVersionNum().toLowerCase().contains("v")) {
                    vo.setIosVersionCode(appVersion1.getVersionNum().substring(1));
                    vo.setAndroidVersionCode(appVersion1.getVersionNum().substring(1));
                }else {
                    vo.setIosVersionCode(appVersion1.getVersionNum());
                    vo.setAndroidVersionCode(appVersion1.getVersionNum());
                }
                vo.setAndroidUrl(appVersion1.getDownloadUrl());
                vo.setIosUrl(appVersion1.getDownloadUrl());
                vo.setIosVersionName(appVersion1.getVersionNum());
                vo.setAndroidVersionName(appVersion1.getVersionNum());
                vo.setQrCodeAuth("0");
            }else {
                vo.setUpdateContent(appVersion.getPopupCopyWriting());
                if (appVersion.getVersionNum().toLowerCase().contains("v")) {
                    vo.setIosVersionCode(appVersion.getVersionNum().substring(1));
                    vo.setAndroidVersionCode(appVersion.getVersionNum().substring(1));
                }else {
                    vo.setIosVersionCode(appVersion.getVersionNum());
                    vo.setAndroidVersionCode(appVersion.getVersionNum());
                }
                vo.setAndroidUrl(appVersion.getDownloadUrl());
                vo.setIosUrl(appVersion.getDownloadUrl());
                vo.setIosVersionName(appVersion.getVersionNum());
                vo.setAndroidVersionName(appVersion.getVersionNum());
                vo.setQrCodeAuth("0");
            }
            return vo;
        }
        return null;
    }

    @Override
    public ConfigVo getAndroidVersionConfig(String version, Integer platformType) {
        List<AppVersion> versionList = appVersionService.queryAppVersionByVersionNum(version, platformType);
        if (!CollectionUtils.isEmpty(versionList)){
            ConfigVo vo = new ConfigVo();
            AppVersion appVersion = versionList.get(0);

            // 版本状态1最新版本2提示更新3不提示更新4强制更新
            if (appVersion.getVersionState() == AppCommon.VERSION_STATE_ONE){
                vo.setForce("3"); //最新版本  不提示更新
            }else if (appVersion.getVersionState() == AppCommon.VERSION_STATE_TWO
                    || appVersion.getVersionState() == AppCommon.VERSION_STATE_THREE){//2提示更新
                vo.setForce("2");
            }else if (appVersion.getVersionState() == AppCommon.VERSION_STATE_FOUR){
                vo.setForce("1");
            }
            if(appVersion.getVersionState() != AppCommon.VERSION_STATE_ONE) {
                List<AppVersion> newAppVersionList = appVersionService.queryNewVersionData(1, platformType);
                if (!CollectionUtils.isEmpty(newAppVersionList)){
                    appVersion = newAppVersionList.get(0);
                }
            }
                vo.setUpdateContent(appVersion.getPopupCopyWriting());
                if (appVersion.getVersionNum().toLowerCase().contains("v")) {
                    vo.setIosVersionCode(appVersion.getVersionNum().substring(1));
                    vo.setAndroidVersionCode(appVersion.getVersionNum().substring(1));
                }else {
                    vo.setIosVersionCode(appVersion.getVersionNum());
                    vo.setAndroidVersionCode(appVersion.getVersionNum());
                }
                vo.setAndroidUrl(appVersion.getDownloadUrl());
                vo.setIosUrl(appVersion.getDownloadUrl());
                vo.setIosVersionName(appVersion.getVersionNum());
                vo.setAndroidVersionName(appVersion.getVersionNum());
                vo.setQrCodeAuth("0");
            return vo;
        }
        return null;
    }

    private IndexVo buildIndexVo(List<AppPageConfig> list,AppQueryForm form,Long userId,Integer versionValue) {
        IndexVo indexVo = new IndexVo();
        List<AdVo> adVoList = new ArrayList<>();
        List<IconVo> iconVoList = new ArrayList<>();
        List<ModuleVo> moduleVoList = new ArrayList<>();
        indexVo.setIconList(iconVoList);
        indexVo.setBannerList(adVoList);
        indexVo.setModuleList(moduleVoList);
        if (form.getType() == 0){ //首页
            List<AppConfigDTO>  appConfigList = null;
            if (userId != null && userId.longValue() != 0){
                appConfigList =  appConfigService.queryIndexByUserId(userId,versionValue);
            }
            if (userId == null || userId.longValue() == 0 || CollectionUtils.isEmpty(appConfigList)){
                AppConfig appConfig = new AppConfig();
                appConfig.setDefaultIndex(AppCommon.APP_DEFAULT_ONE);
                 appConfigList = appConfigService.queryAppConfigList(appConfig,versionValue);
            }
            if (!CollectionUtils.isEmpty(appConfigList)){
                appConfigList.stream().forEach(appConfigDTO -> {
                    iconVoList.add(buildIconVo(appConfigDTO,form.getPlatformType()));
                });
            }
        }
        for (AppPageConfig appPageConfig : list) {
           switch (appPageConfig.getContentType()){
               case 0: //icon
                   break;
               case 1: //广告
                   adVoList.addAll(buildAdVoList(appPageConfig.getPlaceId(),versionValue));
                   break;
               case 2:
                   break;
               case 3:
               case 4:
               case 5: //3楼层 4 上新 5 横版展示 6主题区
               case 6:
                   moduleVoList.add(buildModuleVo(appPageConfig,form.getPlatformType()));
                   break;

           }
        }
       /* if (type == 1){
            List<AppGroupConfigDTO> groupConfigDTOList = appGroupConfigService.queryAppGroupByType(3, versionValue);
            if (!CollectionUtils.isEmpty(groupConfigDTOList)){
                ModuleVo moduleVo = new ModuleVo();
                moduleVo.setContentType(6);
                moduleVo.setModuleName("主题区");
                moduleVo.setModulePicUrl(null);
                moduleVo.setSubModuleList(setModuleLinkListForDTO(groupConfigDTOList));
                moduleVoList.add(moduleVo);
            }
        }*/
        return indexVo;
    }

    private ModuleVo buildModuleVo(AppPageConfig appPageConfig,int PlatformType) {
        ModuleVo moduleVo = new ModuleVo();
        moduleVo.setContentType(appPageConfig.getContentType());
        moduleVo.setModuleName(appPageConfig.getModuleName());
        moduleVo.setModulePicUrl(appPageConfig.getCustomIconUrl());
        List<AppGroupConfig> appGroupConfigList = appPageConfig.getAppGroupConfigList();
        if (!CollectionUtils.isEmpty(appGroupConfigList)){
            moduleVo.setSubModuleList(setModuleLinkList(appGroupConfigList,PlatformType));
        }
        return moduleVo;
    }
    private List<ModuleVo> setModuleLinkListForDTO(List<AppGroupConfigDTO> appGroupConfigList,int PlatformType) {
        List<ModuleVo>  list = new ArrayList<>();
        appGroupConfigList.stream().forEach(appGroupConfig -> {
            ModuleVo moduleVO = new ModuleVo();
            moduleVO.setModuleName(appGroupConfig.getName());
            moduleVO.setModulePicUrl(appGroupConfig.getCustomIconUrl());
            List<AppConfigDTO> appConfigList = appGroupConfig.getAppConfigList();
            if (!CollectionUtils.isEmpty(appConfigList)){
                List<IconVo> linkList = new ArrayList<>();
                appConfigList.stream().forEach(appConfig -> {
                    linkList.add(buildIconVo(appConfig,PlatformType));
                });
                moduleVO.setLinkList(linkList);
            }
            list.add(moduleVO);
        });
        return list;
    }
    private List<ModuleVo> setModuleLinkList(List<AppGroupConfig> appGroupConfigList,int PlatformType) {
        List<ModuleVo>  list = new ArrayList<>();
        appGroupConfigList.stream().forEach(appGroupConfig -> {
            ModuleVo moduleVO = new ModuleVo();
            moduleVO.setModuleName(appGroupConfig.getName());
            moduleVO.setModulePicUrl(appGroupConfig.getCustomIconUrl());
            List<AppConfig> appConfigList = appGroupConfig.getAppConfigList();
            if (!CollectionUtils.isEmpty(appConfigList)){
                List<IconVo> linkList = new ArrayList<>();
                appConfigList.stream().forEach(appConfig -> {
                    linkList.add(buildIconVo(appConfig,PlatformType));
                });
                moduleVO.setLinkList(linkList);
            }
            list.add(moduleVO);
        });
        return list;
    }
    private IconVo buildIconVo(AppConfig appConfig,int PlatformType){
        IconVo iconVO = new IconVo();
        iconVO.setIconId(appConfig.getId());
        iconVO.setAppId(appConfig.getAppId());
        iconVO.setAppName(appConfig.getName());
        iconVO.setAppIconUrl(appConfig.getCustomIconUrl());
        if (appConfig.getNavType() == 2){
            if (PlatformType == 1) {
                iconVO.setAppStartUrl(appConfig.getH5TempIosUrl());
            }else {
                iconVO.setAppStartUrl(appConfig.getH5TempAndroidUrl());
            }
        }else {
            iconVO.setAppStartUrl(appConfig.getAppStartUrl());
        }
        iconVO.setAppType(appConfig.getAppType());
        iconVO.setAndroidGoPage(appConfig.getAndroidGoPage());
        iconVO.setIosGoPage(appConfig.getIosGoPage());
        iconVO.setLogin(appConfig.getLogin());
        iconVO.setGroupInfoId(appConfig.getGroupInfoId());
        iconVO.setAuthorize(appConfig.getAuthorize());
        iconVO.setUneditable(appConfig.getEditFlag()== 0?1:0); //
        iconVO.setAddToolbar(appConfig.getIsTitle());
        return iconVO;
    }
    private IconVo buildIconVo(AppConfigDTO appConfigDTO,int PlatformType){ //PlatformType 版本类型 1 iOS 2android
        IconVo iconVO = new IconVo();
        iconVO.setIconId(appConfigDTO.getId());
        iconVO.setAppId(appConfigDTO.getAppId());
        iconVO.setAppName(appConfigDTO.getName());
        iconVO.setAppIconUrl(appConfigDTO.getCustomIconUrl());
        if (appConfigDTO.getNavType() == 2){
            if (PlatformType == 1) {
                iconVO.setAppStartUrl(appConfigDTO.getH5TempIosUrl());
            }else {
                iconVO.setAppStartUrl(appConfigDTO.getH5TempAndroidUrl());
            }
        }else {
            iconVO.setAppStartUrl(appConfigDTO.getAppStartUrl());
        }
        iconVO.setAppType(appConfigDTO.getAppType());
        iconVO.setAndroidGoPage(appConfigDTO.getAndroidGoPage());
        iconVO.setIosGoPage(appConfigDTO.getIosGoPage());
        iconVO.setLogin(appConfigDTO.getLogin());
        iconVO.setGroupInfoId(appConfigDTO.getGroupInfoId());
        iconVO.setAuthorize(appConfigDTO.getAuthorize());
        if (appConfigDTO.getEditFlag() !=null) {
            iconVO.setUneditable(appConfigDTO.getEditFlag() == 0 ? 1 : 0);
        }else{
            iconVO.setUneditable(1);
        }
        iconVO.setAddToolbar(appConfigDTO.getIsTitle());

        return iconVO;
    }
    private List<AdVo> buildAdVoList(String placeId,Integer versionValue) {
        List<AppAdvertDTO> list = appAdvertService.queryAdvertListByPlaceId(Long.valueOf(placeId),versionValue);
        List<AdVo> adVoList = new ArrayList<>();
        for (AppAdvertDTO adDetail : list) {
            AdVo adVO = new AdVo();
            adVO.setAppName(adDetail.getName());
            adVO.setAppId(adDetail.getAppId());
            adVO.setAppIconUrl(adDetail.getImage());
            adVO.setIosGoPage(adDetail.getIosGoPage());
            adVO.setAndroidGoPage(adDetail.getAndroidGoPage());
            adVO.setAppStartUrl(adDetail.getAppStartUrl());
            adVO.setLogin( adDetail.getLogin());
            adVO.setAppType(adDetail.getAppType());
            adVO.setAddToolbar(adDetail.getIsTitle());
            adVO.setGroupInfoId(adDetail.getGroupInfoId());
            adVO.setAuthorize(adDetail.getAuthorize());
            adVoList.add(adVO);
        }
        return adVoList;
    }
}
